package org.lex.io.filesystem;

import java.io.File;
import java.util.Collections;
import java.util.Vector;

import javax.swing.filechooser.FileFilter;

public class PostfixFileFilter extends FileFilter {
	private static final String DEFAULT_DESCRIPTION = "Default File Filter";
	private static final String[] EMPTY_ARRAY = new String[0];

	private Vector<String> fileExtensions = null;
	private boolean acceptFilesOnlyInExtensions = true;
	private String descriptiuon = DEFAULT_DESCRIPTION;

	public PostfixFileFilter() {
		this(true);
	}

	public PostfixFileFilter(boolean acceptFilesOnlyInExtensions) {
		super();
		this.fileExtensions = new Vector<String>();
		this.acceptFilesOnlyInExtensions = acceptFilesOnlyInExtensions;
	}

	public void addExtension(String... exts) {
		if (null == exts || 0 == exts.length)
			return;
		// �ö��ַ���������չ��ʹ����չ����б?������״̬
		for (int i = 0; i < exts.length; i++) {
			String ext = exts[i].toLowerCase();
			int index = Collections.binarySearch(this.fileExtensions, ext);
			if (index < 0)
				this.fileExtensions.insertElementAt(ext, -index - 1);
		}
	}

	public boolean removeExtension(String ext) {
		return this.fileExtensions.remove(ext.toLowerCase());
	}

	public String[] getExtensions() {
		if (0 == this.fileExtensions.size())
			return EMPTY_ARRAY;
		return fileExtensions.toArray(new String[this.fileExtensions.size()]);
	}

	@Override
	public boolean accept(File f) {
		if (true == f.isDirectory())
			return true;
		int index = Collections.binarySearch(fileExtensions, getFileExtension(f));
		if (index < 0)
			return !acceptFilesOnlyInExtensions;
		return acceptFilesOnlyInExtensions;
	}

	public String getDescription() {
		return this.toString();
	}

	public void setDescription(String description) {
		this.descriptiuon = description;
	}

	private String getFileExtension(File f) {
		return FileNameUtilities.getExtension(f.getName()).toLowerCase();
	}

	public String toString() {
		StringBuilder buffer = new StringBuilder();
		buffer.append(this.descriptiuon).append(" (");
		for (int i = 0; i < this.fileExtensions.size(); i++) {
			String ext = this.fileExtensions.get(i);
			buffer.append("*.").append(ext).append(' ');
		}
		if (buffer.length() >= 1)
			buffer.setLength(buffer.length() - 1);
		buffer.append(')');
		return buffer.toString();
	}
}
